import { app, shell, BrowserWindow, dialog, ipcMain } from 'electron'
import { join } from 'path'
import { networkInterfaces } from 'os'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import axios from 'axios'
import icon from '../../resources/icon.png?asset'
import request from './request'
import Store from 'electron-store'
const path = require('path')
const fs = require('fs')
const { Blob } = require('buffer')
const store = new Store()
function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 900,
    height: 670,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })
  // 开启开发工具DevTools
  mainWindow.webContents.openDevTools()
  // 获取ip
  function getLocalIP() {
    const interfaces = networkInterfaces()
    for (const name of Object.keys(interfaces)) {
      for (const iface of interfaces[name]) {
        // 跳过内部 IP 和 IPv6
        if (iface.family === 'IPv4' && !iface.internal) {
          return iface.address // 返回第一个符合条件的 IP
        }
      }
    }
    return '' // 默认返回本地回环地址
  }
  // 提供一个 IPC 方法供渲染进程调用
  ipcMain.handle('get-local-ip', () => {
    return getLocalIP()
  })

  // IPC 通信：允许渲染进程设置 store 数据
  ipcMain.handle('set-store-data', (event, key, value) => {
    store.set(key, value) // 主进程调用 electron-store 的 set 方法
  })

  // IPC 通信：允许渲染进程获取 store 数据
  ipcMain.handle('get-store-data', (event, key) => {
    return store.get(key) // 主进程调用 electron-store 的 set 方法
  })
  // 监听 userInfo 变化
  store.onDidChange('user-info', (newValue) => {
    // 通知所有渲染进程
    BrowserWindow.getAllWindows().forEach((win) => {
      win.webContents.send('USER_INFO_CHANGED', newValue)
    })
  })
  // 监听 request.js 触发的 CHANGE_STATUS 事件
  ipcMain.on('CHANGE-STATUS', (data) => {
    mainWindow.webContents.send('change-status', data)
  })
  ipcMain.handle('delete-user', (event, key) => {
    console.log('删除')
    store.clear()
  })
  // IPC 通信：获取打印机列表
  ipcMain.handle('get-printer-list', async () => {
    const printers = await mainWindow.webContents.getPrintersAsync()
    return printers
  })
  // 上传文件
  ipcMain.handle('upload:files', async (event, data, _object) => {
    const result = await dialog.showOpenDialog({
      properties: ['openFile'],
      filters: [{ name: '图片', extensions: ['png', 'jpg'] }]
    })
    const filePath = result.filePaths[0]
    const fileData = fs.readFileSync(filePath)
    const blob = new Blob([fileData], { type: 'application/octet-stream' })
    const file = new File([blob], path.basename(filePath), {
      type: blob.type
    })
    const formData = new FormData()
    formData.append('file', file)
    event.sender.send('loading-state', { show: true })

    try {
      const response = await request[data.methods](data.url, formData, _object)
      return response
    } catch (error) {
      throw new Error(`上传失败：${error.message}`)
    } finally {
      // 6. 无论成功/失败，通知渲染进程：隐藏 Loading
      event.sender.send('loading-state', { show: false })
    }
  })
  //请求
  ipcMain.handle('fetch-data', async (event, data, _object) => {
    const response = await request[data.methods](data.url, data.params, _object)
    return response
  })
  // change-main
  ipcMain.on('change-main', (event, data) => {
    switch (data.key) {
      case 'toggle-fullscreen':
        if (data.value === 'unmaximize') {
          console.log('unmaximize');
          mainWindow.unmaximize(); // 还原窗口
        } else {
          console.log('maximize');
          mainWindow.maximize(); // 最大化窗口
        }
        break;
      case 'close':
        app.quit();
        break;
    }
  })
  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  createWindow()
  // IPC 通信：监听渲染进程的打印请求
  ipcMain.handle('print-page', async (event, pdfUrl, options) => {
    // 1. 创建新窗口
    const printWindow = new BrowserWindow({
      show: true, // 显示窗口（默认 true）
      webPreferences: {
        contextIsolation: true,
        nodeIntegration: false
      }
    })
    // 2. 加载 PDF URL
    printWindow.loadURL(pdfUrl)

    printWindow.close()
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        // 调用打印，不设置 silent: true，会弹出系统打印对话框

        // printWindow.webContents.print(
        //   options,
        //   (success, errorType) => {
        //     if (!success) {
        //       console.error('打印失败:', errorType)
        //       reject(errorType)
        //       printWindow.close();
        //     } else {
        //       console.log('打印已触发（用户点击了打印按钮）')
        //       resolve(true)
        //       printWindow.close();
        //     }
        //   }
        // )
      }, 20000) // 延迟 20 秒（根据网络情况调整）
    })
  })
  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})
// 监听渲染进程的下载请求（IPC 通道：download-pdf）
ipcMain.on('download-pdf', async (event, pdfUrl, fileName) => {
  try {
    // 1. 获取用户选择的保存路径
    const savePath = await dialog.showSaveDialog({
      defaultPath: fileName || '下载', // 默认保存到「下载」目录
      filters: [{ name: 'PDF 文件', extensions: ['pdf'] }]
    });

    if (savePath.canceled) {
      event.reply('download-status', { success: false, message: '用户取消下载' })
      return
    }

    // 2. 下载远程 PDF 数据
    const response = await axios.get(pdfUrl, {
      responseType: 'arraybuffer' // 关键：获取二进制数据
    })

    // 3. 写入本地文件
    await fs.writeFile(savePath.filePath, response.data);

    event.reply('download-status', { success: true, message: '下载成功' });
  } catch (error) {
    event.reply('download-status', { success: false, message: `下载失败：${error.message}` });
  }
})


// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
